package com.fileupload.upload.log.strategy;

import com.fileupload.mapper.FileUploadLogMapper;
import com.fileupload.model.entity.FileUploadLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * MySQL日志存储策略实现
 * 使用数据库进行日志存储
 */
@Component("mySqlLogStorageStrategy")
public class MySqlLogStorageStrategy implements LogStorageStrategy {
    
    private static final Logger logger = LoggerFactory.getLogger(MySqlLogStorageStrategy.class);
    
    @Autowired
    private FileUploadLogMapper fileUploadLogMapper;
    
    @Override
    public boolean storeLog(FileUploadLog log) {
        if (log == null) {
            logger.warn("[MySQL存储] 日志对象为空，跳过存储");
            return false;
        }
        
        try {
            // 单条日志存储，使用批量存储方法包装
            return batchStoreLogs(Collections.singletonList(log));
        } catch (Exception e) {
            logger.error("[MySQL存储] 单条日志存储失败: {}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public boolean batchStoreLogs(List<FileUploadLog> logs) {
        if (logs == null || logs.isEmpty()) {
            logger.warn("[MySQL存储] 日志列表为空，跳过批量存储");
            return false;
        }
        
        try {
            logger.info("[MySQL存储] 开始执行数据库批量插入，记录数: {}", logs.size());
            long startTime = System.currentTimeMillis();
            
            // 调用Mapper进行批量插入
            int result = fileUploadLogMapper.batchInsert(logs);
            
            long endTime = System.currentTimeMillis();
            logger.info("[MySQL存储] 数据库批量插入成功完成 - 记录数: {}, 耗时: {}ms, 平均每条: {:.2f}ms", 
                    result, (endTime - startTime), 
                    (double)(endTime - startTime) / Math.max(1, result));
            
            return result > 0;
        } catch (Exception e) {
            logger.error("[MySQL存储] 批量插入失败: {}", e.getMessage(), e);
            throw e; // 抛出异常让调用方处理
        }
    }
    
    @Override
    public String getType() {
        return "mysql"; // 返回策略类型标识
    }
}